package top.go2do.websiteNavigation.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * @author xingyuji
 * @date 2023/9/26 17:50
 * @description
 */
public class ImageUtils {
    public static String imgUrl2Base64Code(String picUrl) throws IOException {
        String encoder = "data:image/jpg;base64,";
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        URL url = new URL(picUrl);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        InputStream is = connection.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = is.read(bytes)) != -1) {
            data.write(bytes, 0, len);
        }
        is.close();
        Base64.Encoder base64Encoder = Base64.getEncoder(); // 获取标准编码器
        // 直接编码并存储，无需替换换行符
        encoder = encoder + base64Encoder.encodeToString(data.toByteArray());
        return encoder;
    }
}
